<template>
  <div>
    <div>
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>角色管理</el-breadcrumb-item>
        <el-breadcrumb-item>角色列表</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" size="small">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table :data="rolesList" border stripe>
        <el-table-column type="expand">
          <template v-slot="scoped">
            <div>
              <el-row
                :class="['bdbottom',k1 == 0 ? 'bdtop' :'','vcenter']"
                v-for="(item1, k1) in scoped.row.children"
                :key="scoped.row.id"
              >{{scoped.row.id}}
                <!-- 渲染一级 -->
                <el-col :span="5">
                  <el-tag
                    closable
                    type="primary"
                    @close="removeRightById(scoped.row, item1.id)"
                    :key="item1.id"
                  >{{item1.authName}}</el-tag>
                  <i class="el-icon-arrow-right"></i>
                </el-col>
                <!-- 渲染二级和三级 -->
                <el-col :span="19">
                  <el-row
                    :class="[k2 == 0 ? '' :'bdtop','vcenter']"
                    v-for="(item2, k2) in item1.children"
                  >
                    <!-- 渲染二级 -->
                    <el-col :span="6">
                      <el-tag
                        closable
                        type="success"
                        @close="removeRightById(scoped.row, item2.id)"
                        :key="item2.id"
                      >{{item2.authName}}</el-tag>
                      <i class="el-icon-arrow-right"></i>
                    </el-col>
                    <!-- 渲染三级 -->
                    <el-col :span="18">
                      <el-row :class="['vcenter']" v-for="(item3, k3) in item2.children">
                        <el-col>
                          <el-tag
                            closable
                            type="info"
                            @close="removeRightById(scoped.row, item3.id)"
                            :key="item3.id"
                          >{{item3.authName}}</el-tag>
                        </el-col>
                      </el-row>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="#" type="index" align="center"></el-table-column>
        <el-table-column label="角色名称" prop="roleName" align="center"></el-table-column>
        <el-table-column label="描述信息" prop="roleDesc" align="center"></el-table-column>
        <el-table-column label="操作" align="center">
          <template v-slot="scoped">
            <div>
              <el-button size="small" type="success" round icon="el-icon-edit">编辑</el-button>
              <el-button size="small" type="danger" round icon="el-icon-delete">删除</el-button>
              <el-button
                size="small"
                type="warning"
                round
                icon="el-icon-setting"
                @click="showSetRightsDialog(scoped.row)"
              >分配权限</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限弹窗 -->
    <el-dialog title="分配角色权限" :visible.sync="setRightsDialogVisiable" width="50%" @close="setRightsDialogClose">
      <el-tree
        ref="setRolesRights"
        :data="rightsList"
        :props="rightsProps"
        show-checkbox
        node-key="id"
        default-expand-all
        check-on-click-node
        :default-checked-keys="leafKeys"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightsDialogVisiable = false">取 消</el-button>
        <el-button type="primary" @click="setRoleRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      rolesList: [],
      rowId: 0,
      setRightsDialogVisiable: false,
      rightsList: [],
      rightsProps: {
        children: "children",
        label: "authName",
      },
      leafKeys: [], //当前行已有的三级权限id
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status != 200)
        return this.$message.error("获取角色列表失败！");
      this.rolesList = res.data;
    },
    async removeRightById(row, rightId) {
      const result = await this.$confirm(
        "此操作将永久删除该权限, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (result == "cancel") return this.$message.info("用户取消了操作");
      const { data: res } = await this.$http.delete(
        `roles/${row.id}/rights/${rightId}`
      );
      if (res.meta.status != 200)
        return this.$message.error("删除指定权限失败！");
      row.children = res.data;
      this.$message.success("删除权限成功！");
    },
    //递归获取当前角色的所有三级权限id，存入arr中。
    getLeafKeys(data, arr){
        if(!data.children){
            return arr.push(data.id);
        }else{
            data.children.forEach(item => this.getLeafKeys(item, arr));
        }
    },
    async showSetRightsDialog(row) {
      this.rowId = row.id;
      const { data: res } = await this.$http.get("rights/tree");
      if (res.meta.status != 200) return this.$message.error("获取权限树列表失败！");
      this.rightsList = res.data;
      this.getLeafKeys(row, this.leafKeys);
      console.log(this.leafKeys);
      this.setRightsDialogVisiable = true;
    },
    setRightsDialogClose(){
        this.leafKeys = [];
    },
    async setRoleRights(){
        const keys = [...this.$refs.setRolesRights.getCheckedKeys(),...this.$refs.setRolesRights.getHalfCheckedKeys()];
        const idKeys = keys.join(',');
        const {data: res} = await this.$http.post(`roles/${this.rowId}/rights`,{rids: idKeys});
        if(res.meta.status != 200) return this.$message.error('更新权限失败！');
        this.$message.success('更新权限成功！');
        this.getRolesList();
        this.setRightsDialogVisiable = false;
    }
  },
};
</script>

<style lang="less" scoped>
.el-card {
  margin-top: 15px;
}
.el-table {
  margin-top: 15px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
  margin: 5px;
}
</style>